package com.lin.filter;


import com.lin.security.SecurityUser;
import com.lin.security.util.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author linze
 * @version 1.0
 * @Description
 * @Date 2021/1/21 18:03
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JwtUtils.TOKEN_HEADER);

        if(tokenHeader==null||!tokenHeader.startsWith(JwtUtils.TOKEN_PREFIX)){
            chain.doFilter(request,response);
            return;
        }

        SecurityContextHolder.getContext().setAuthentication(this.getAuthentication(tokenHeader));
        super.doFilterInternal(request,response,chain);
    }

    private Authentication getAuthentication(String tokenHeader) {
        String token=tokenHeader.substring(JwtUtils.TOKEN_PREFIX.length());
        if(JwtUtils.isTokenExpired(token)){
            return null;
        }
        Integer uid=JwtUtils.getUidFromToken(token);

        String username=JwtUtils.getUsernameFromToken(token);
        SecurityUser securityUser = JwtUtils.getSecurityUserFromToken(token);
        return new UsernamePasswordAuthenticationToken(uid,securityUser,new ArrayList<>());

    }
}
